<template>
  <div class="tabs-box">
    <div class="tabs-menu" v-show="tabsMenuList?.length">
      <el-tabs v-model="tabsMenuValue" type="card" @tab-click="tabClick" @tab-remove="tabRemove">
        <el-tab-pane v-for="item in tabsMenuList" :key="item.path" :label="item.title" :name="item.path" :closable="item.close">
          <template #label>
            <el-icon class="tabs-icon" v-show="item.icon && tabsIcon">
              <component :is="item.icon"></component>
            </el-icon>
            {{ item.title }}
          </template>
        </el-tab-pane>
      </el-tabs>
      <MoreButton />
    </div>
  </div>
</template>

<script setup lang="ts">
import Sortable from "sortablejs";
import { ref, computed, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useGlobalStore } from "@/stores/modules/global";
import { useTabsStore } from "@/stores/modules/tabs";
import { useAuthStore } from "@/stores/modules/auth";
import { useMenuStore } from "@/stores/modules/menu";
import { routerMap } from "@/utils/routerData";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { TabsPaneContext, TabPaneName } from "element-plus";
import { MatchMenuIdx, MenuItem } from "../../interfaces";
import MoreButton from "./components/MoreButton.vue";

const route = useRoute();
const router = useRouter();
const tabStore = useTabsStore();
const authStore = useAuthStore();
const globalStore = useGlobalStore();
const keepAliveStore = useKeepAliveStore();
const menuStore = useMenuStore();
const tabsMenuValue = ref(route.fullPath);

const tabsIcon = computed(() => globalStore.tabsIcon);
const activeMenuIdx = computed(() => menuStore.activeMenuIdx);

const tabsMenuList = computed(() => {
  if (activeMenuIdx.value < 0) {
    return [];
  }
  return tabStore.tabsMenuList[activeMenuIdx.value]?.values;
});

const isMatched = ref(false);

// tabs 拖拽排序
const tabsDrop = () => {
  Sortable.create(document.querySelector(".el-tabs__nav") as HTMLElement, {
    draggable: ".el-tabs__item",
    animation: 300,
    onEnd({ newIndex, oldIndex }) {
      const tabsList = tabsMenuList.value !== undefined ? [...tabsMenuList.value] : [];
      const currRow = tabsList.splice(oldIndex as number, 1)[0];
      tabsList.splice(newIndex as number, 0, currRow);
      tabStore.setTabs(activeMenuIdx.value, tabsList);
    }
  });
};

// 初始化需要固定的 tabs
const initTabs = () => {
  authStore.flatMenuListGet.forEach(item => {
    if (item.meta.isAffix && !item.meta.isHide && !item.meta.isFull) {
      const tabsParams = {
        icon: item.meta.icon,
        title: item.meta.title,
        path: item.path,
        name: item.name,
        close: !item.meta.isAffix
      };
      tabStore.addTabs(activeMenuIdx.value, tabsParams);
    }
  });
};

// Tab Click
const tabClick = (tabItem: TabsPaneContext) => {
  const fullPath = tabItem.props.name as string;
  router.push(fullPath);
};

// Remove Tab
const tabRemove = (fullPath: TabPaneName) => {
  const name = tabsMenuList.value !== undefined ? tabsMenuList.value.filter(item => item.path == fullPath)[0].name || "" : "";
  keepAliveStore.removeKeepAliveName(name);
  tabStore.removeTabs(activeMenuIdx.value, fullPath as string, fullPath == route.fullPath);
};

/**
 * 根据路由匹配主菜单
 */
const matchMenuIdx: MatchMenuIdx = function (key: number, values: Menu.MenuOptions[], tabsParams?: any): number {
  let matchVal: number = 0;

  values.some((item: MenuItem): void => {
    if (!isMatched.value) {
      if (item.name === route.name) {
        matchVal = key;
        isMatched.value = true;
        tabStore.addTabs(activeMenuIdx.value, tabsParams);
        route.meta.isKeepAlive && keepAliveStore.addKeepAliveName(route.name as string);
        return;
      } else {
        if (item.children && item.children.length > 0) {
          matchVal = matchMenuIdx(key, item.children, tabsParams);
        }
      }
    }
  });
  return matchVal;
};

onMounted(() => {
  tabsDrop();
  initTabs();
});

// 监听路由的变化（防止浏览器后退/前进不变化 tabsMenuValue）
watch(
  () => route.fullPath,
  () => {
    isMatched.value = false;
    if (route.meta.isFull) return;
    tabsMenuValue.value = route.fullPath;
    const tabsParams = {
      icon: route.meta.icon as string,
      title: route.meta.title as string,
      path: route.fullPath,
      name: route.name as string,
      close: !route.meta.isAffix
    };

    const subMenuItemList = activeMenuIdx.value > -1 ? JSON.parse(JSON.stringify(routerMap.get(activeMenuIdx.value))) : undefined;
    subMenuItemList && menuStore.setMenuIdx(matchMenuIdx(activeMenuIdx.value, subMenuItemList, tabsParams));
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
